import selenium.webdriver.common.driver_finder
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select

import time
class Base():
    # 初始化驱动
    def __init__(self, driver):
        self.driver = driver

    # 封装元素定位显示等待方法
    def find_element(self, loc):
        # 异常处理
        try:
            # 显示等待方法
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            # 返回定位元素
            return self.driver.find_element(*loc)
        # 异常处理
        except Exception as e:
            print(e)
            # 报错时截屏
            self.save_time()

    def open_url(self, url):
        self.driver.get(url)

    def clear(self, loc):
        self.find_element(loc).clear()

    # 封装带有时间戳的截屏方法
    def save_time(self):
        t = time.strptime('%Y%m%d-%H%M%S', time.localtime())
        self.driver.save_screenshot('./pag' + t + '.png')

    # 点击元素封装
    def click(self, loc):
        self.find_element(loc).click()

    # 封装元素输入方法
    def send_keys(self, loc, info):
        self.find_element(loc).send_keys(info)

    # 封装文本方法
    def text(self, loc):
        return self.find_element(loc).text

    # 封装进入框架方法
    def iframe(self, loc):
        self.driver.switch_to.frame(self.find_element(loc))

    # 封装退出框架方法
    def iframe_contend(self):
        self.driver.switch_to.default_content()

    # 封装滚动顶部方法
    def scrollTo(self):
        self.driver.execute_script('window.scrollTo(0,0)')

    # 封装滚动到底部方法
    def scrollTo_Height(self):
        self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')

    # 封装到任意位置方法
    def scrollTo_x(self, x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    # 弹窗确定
    def accept(self):
        self.driver.switch_to.alert.accept()

    # 弹窗取消
    def dismiss(self):
        self.driver.switch_to.alert.dismiss()

    # 切窗口
    def switch_to_window_handles(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    #强制等待
    def sleep(self, loc):
        time.sleep(loc)


